<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="小说ID" prop="novelId">
        <el-input
          v-model="queryParams.novelId"
          placeholder="请输入小说ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入章节标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节顺序" prop="chapterOrder">
        <el-input
          v-model="queryParams.chapterOrder"
          placeholder="请输入章节顺序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字数" prop="wordCount">
        <el-input
          v-model="queryParams.wordCount"
          placeholder="请输入字数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否免费" prop="isFree">
        <el-select v-model="queryParams.isFree" placeholder="请选择是否免费" clearable>
          <el-option label="免费" :value="1" />
          <el-option label="收费" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['novel:chapters:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['novel:chapters:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['novel:chapters:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['novel:chapters:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-document"
          size="mini"
          :disabled="multiple"
          @click="handleBatchImportWord"
          v-hasPermi="['novel:chapters:edit']"
        >批量解析</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chaptersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="章节ID" align="center" prop="chapterId" width="80" />
      <el-table-column label="小说ID" align="center" prop="novelId" width="80" />
      <el-table-column label="章节标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="章节内容" align="center" prop="content" :show-overflow-tooltip="true" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.content && scope.row.content.length > 20 ? scope.row.content.substring(0, 20) + '...' : scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="章节顺序" align="center" prop="chapterOrder" width="90" />
      <el-table-column label="字数" align="center" prop="wordCount" width="90" />
      <el-table-column label="是否免费" align="center" prop="isFree" width="90">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isFree === 1 ? 'success' : 'warning'">
            {{ scope.row.isFree === 1 ? '免费' : '收费' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleImportWord(scope.row)"
            v-hasPermi="['novel:chapters:edit']"
          >解析</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['novel:chapters:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['novel:chapters:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改小说章节对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="小说ID" prop="novelId">
          <el-input v-model="form.novelId" placeholder="请输入小说ID" />
        </el-form-item>
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="章节内容" prop="content">
          <file-upload v-model="form.content"/>
        </el-form-item>
        <el-form-item label="章节顺序" prop="chapterOrder">
          <el-input v-model="form.chapterOrder" placeholder="请输入章节顺序" type="number" />
        </el-form-item>
        <el-form-item label="字数" prop="wordCount">
          <el-input v-model="form.wordCount" placeholder="请输入字数" type="number" />
        </el-form-item>
        <el-form-item label="是否免费" prop="isFree">
          <el-radio-group v-model="form.isFree">
            <el-radio :label="1">免费</el-radio>
            <el-radio :label="0">收费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChapters, getChapters, delChapters, addChapters, updateChapters, importWordContent } from "@/api/novel/chapters"

export default {
  name: "Chapters",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小说章节表格数据
      chaptersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        novelId: null,
        title: null,
        content: null,
        chapterOrder: null,
        wordCount: null,
        isFree: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        novelId: [
          { required: true, message: "小说ID不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "章节标题不能为空", trigger: "blur" }
        ],
        chapterOrder: [
          { required: true, message: "章节顺序不能为空", trigger: "blur" }
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedAt: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询小说章节列表 */
    getList() {
      this.loading = true
      listChapters(this.queryParams).then(response => {
        this.chaptersList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        chapterId: null,
        novelId: null,
        title: null,
        content: null,
        chapterOrder: null,
        wordCount: null,
        isFree: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.chapterId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加小说章节"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const chapterId = row.chapterId || this.ids
      getChapters(chapterId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改小说章节"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.chapterId != null) {
            updateChapters(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addChapters(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chapterIds = row.chapterId || this.ids
      this.$modal.confirm('是否确认删除小说章节编号为"' + chapterIds + '"的数据项？').then(function() {
        return delChapters(chapterIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('novel/chapters/export', {
        ...this.queryParams
      }, `chapters_${new Date().getTime()}.xlsx`)
    },
    /** 解析Word文档按钮操作 */
    handleImportWord(row) {
      const chapterId = row.chapterId
      this.$modal.confirm('是否确认解析章节"' + row.title + '"的Word文档内容？').then(() => {
        this.loading = true
        return importWordContent(chapterId)
      }).then(() => {
        this.loading = false
        this.getList()
        this.$modal.msgSuccess("解析成功")
      }).catch(() => {
        this.loading = false
      })
    },
    /** 批量解析Word文档按钮操作 */
    handleBatchImportWord() {
      const chapterIds = this.ids
      const chapterCount = chapterIds.length
      this.$modal.confirm('是否确认批量解析选中的' + chapterCount + '个章节的Word文档内容？').then(() => {
        this.loading = true
        let successCount = 0
        let failCount = 0
        const errors = []
        
        // 使用 Promise.all 处理所有章节
        const promises = chapterIds.map(chapterId => {
          return importWordContent(chapterId)
            .then(() => {
              successCount++
            })
            .catch(error => {
              failCount++
              errors.push({ chapterId, error: error.msg || '解析失败' })
            })
        })
        
        Promise.all(promises).finally(() => {
          this.loading = false
          this.getList()
          
          if (failCount === 0) {
            this.$modal.msgSuccess(`批量解析完成！成功: ${successCount}个`)
          } else {
            this.$modal.msgWarning(`批量解析完成！成功: ${successCount}个，失败: ${failCount}个`)
          }
        })
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>
